<template>
  <page-layout>
    <a-spin :spinning="isLoading">
      <a-card>
        <a-button type="primary" @click="handleSave">{{
          t("button.save")
        }}</a-button>
      </a-card>
      <a-card title="基础信息">
        <a-form ref="formRef" :model="formData.data" :label-col="labelCol" :rules="rules">
          <a-row>
            <a-col :span="8">
              <a-form-item label="课程编码">
                <a-input v-model:value="formData.data.code" readonly :placeholder="t('placeholder.create')"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.school')" name="schName">
                <a-input v-model:value="formData.data.schName"
                         readonly
                         :placeholder="t('placeholder.pleaseSelect')">
                  <template #addonAfter>
                    <div
                      class="primary-color cursor-pointer"
                      @click="handleOpenSchoolModal('base')"
                    >
                      {{ t('button.select') }}
                    </div>
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-code.label.subjectCategory')" name="disciplineId">
                <a-tree-select
                  v-model:value="formData.data.disciplineId"
                  v-model:searchValue="formData.data.disciplineName"
                  style="width: 100%"
                  showSearch
                  treeNodeFilterProp="disciplineName"
                  :dropdown-style="{ maxHeight: '360px', overflow: 'auto' }"
                  :tree-data="formData.subjectList"
                  placeholder="学科类别"
                  replace
                  tree-default-expand-all
                  :replaceFields="replaceFields"
                  @select="handleTree"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.courseCode')" name="courseCode">
                <a-input v-model:value="formData.data.courseCode" :placeholder="t('placeholder.pleaseEnter')"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.courseName')" name="courseName">
                <a-input v-model:value="formData.data.courseName" :placeholder="t('placeholder.pleaseEnter')"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.credit')" name="credit">
                <a-input v-model:value="formData.data.credit" :placeholder="t('placeholder.pleaseEnter')"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="课程类型" name="typeId">
                <a-select v-model:value="formData.data.typeId">
                  <a-select-option
                    v-for="(item, index) in dictLists.data[
                      dictEnum.COURSE_TYPE
                    ]"
                    :key="index"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.courseBeforeCode')">
                <a-input v-model:value="formData.data.coursePastCode" :placeholder="t('placeholder.pleaseEnter')"/>
              </a-form-item>
            </a-col>
            <!-- <a-col :span="8">
              <a-form-item
                :label="t('course-manage.label.courseFirstOpenTime')"
              >
                <a-date-picker
                  v-model:value="formData.data.firstCourseStarttime"
                  valueFormat="yyyy-MM-DD"
                  type="date"
                  class="w-100p"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.courseAuditTime')">
                <a-date-picker
                  v-model:value="formData.data.courseLastReviewtime"
                  valueFormat="yyyy-MM-DD"
                  type="date"
                  class="w-100p"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :label="t('course-manage.label.courseLastOpenTime')"
                class="mb-0"
              >
                <a-date-picker
                  v-model:value="formData.data.courseLastOpentime"
                  valueFormat="yyyy-MM-DD"
                  type="date"
                  class="w-100p"
                />
              </a-form-item>
            </a-col> -->
            <a-col :span="8">
              <a-form-item
                :label="t('course-manage.label.courseRemark')"
                name="describes"
              >
                <a-textarea :auto-size="{ minRows: 2, maxRows: 6 }" v-model:value="formData.data.describes"
                      :placeholder="t('placeholder.pleaseEnter')" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item>
                <div style="margin-left: 25px">
                  <a-button
                    type="primary"
                    :disabled="
                      formData.data.preCurriculumRelationshipList.length >= 10
                    "
                    @click="handleCourse"
                    >{{
                      t("course-code.title.newModificationHe")
                    }}</a-button
                  >
                </div>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-row
                v-for="(
                  item, index
                ) in formData.data.preCurriculumRelationshipList"
                :key="index"
              >
                <a-col :span="8">
                  <a-form-item :label="t('course-code.label.preCourse')">
                    <a-input readonly v-model:value="item.courseName">
                      <template #addonAfter>
                        <div
                          class="primary-color cursor-pointer"
                          @click="handleOpenSchoolModal('visiableCourse', index)"
                        >
                          {{ t('button.select') }}
                        </div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item
                    :label="t('course-code.label.preCourseRelationship')"
                  >
                    <a-select v-model:value="item.relationship">
                      <a-select-option
                        v-for="(item, index) in dictLists.data[
                          dictEnum.COURSE_RELATION
                        ]"
                        :key="index"
                        :value="item.value"
                      >
                        {{ item.label }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-button
                    style="margin-left: 20px; margin-top: 10px"
                    type="danger"
                    @click="handleDel(item, index)"
                    >{{ t("button.delete") }}</a-button
                  >
                </a-col>
              </a-row>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
      <a-card title="SOR" class="mt-15">
        <template #extra>
          <a-button
            type="primary"
            ghost
            @click="addCourseItem"
          >
            {{ t("button.add") }}
          </a-button>
          </template>
        <a-form ref="sorFormRef" :model="formData.data">
          <a-row
            v-for="(sorItem, sorIndex) in formData.data.cbiSorList"
            :key="sorIndex"
            :gutter="16"
            type="flex"
            justify="space-between"
            align="bottom"
          >
            <a-col :span="6">
              <a-form-item
                :label="t('course-manage.label.schoolName')"
                :name="['cbiSorList', sorIndex, 'schName']"
                class="mb-0"
              >
                <!-- :rules="requiredRulesS" -->
                <a-input readonly
                         :placeholder="t('placeholder.pleaseSelect')"
                         v-model:value="sorItem.schName"
                >
                  <template #addonAfter>
                    <div
                      class="primary-color cursor-pointer"
                      @click="handleOpenSchoolModal('sor', sorIndex)"
                    >
                      {{ t('button.select') }}
                    </div>
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item
                :label="t('course-manage.label.courseCode')"
                :name="['cbiSorList', sorIndex, 'courseCode']"
                class="mb-0"
              >
                <!-- :rules="requiredRules" -->
                <a-input
                  v-model:value="sorItem.courseCode"
                  :placeholder="placeHolder"
                />
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item
                :label="t('course-manage.label.courseName')"
                :name="['cbiSorList', sorIndex, 'courseName']"
                class="mb-0"
              >
                <!-- :rules="requiredRules" -->
                <a-input
                  v-model:value="sorItem.courseName"
                  :placeholder="placeHolder"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                :label="t('course-manage.label.auditPassTime')"
                :name="['cbiSorList', sorIndex, 'sorAuditTime']"
                class="mb-0"
              >
                <!-- :rules="requiredRulesT" -->
                <a-date-picker
                  v-model:value="sorItem.sorAuditTime"
                  :placeholder="placeHolder"
                  type="date"
                  class="w-100p"
                />
              </a-form-item>
            </a-col>
            <a-col :span="2">
              <a-button
                type="danger"
                ghost
                @click="deleteCourseItem(sorIndex)"
              >
                {{ t("button.delete") }}
              </a-button>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
      <a-card class="mt-15">
        <a-row>
          <a-col :span="24">
            <div class="box-ver-center">
              <div
                v-for="item in formData.data.files"
                :key="item.fileId"
                :style="{ marginLeft: '5px' }"
                class="thumb-item mb-8 mr-10"
              >
                <img :src="item.url" alt="img">
              </div>
              <a-upload
                listType="picture-card"
                :showUploadList="false"
                :customRequest="handleUpload"
              >
                <div v-if="formData.data.files && formData.data.files.length < 4">
                  <plus-outlined />
                  <div class="ant-upload-text">{{t("button.upload")}}</div>
                </div>
              </a-upload>
            </div>
            <div>
              <p>该图片主要显示于小程序</p>
              <p>支持jpg,png格式</p>
              <p>图片尺寸建议498✖️300,大小不超过500kb</p>
            </div>
            <a-modal
              :visible="previewVisible"
              :footer="null"
              @cancel="handleCancel"
            >
              <img alt="缩略图" style="width: 100%" :src="previewImage" />
            </a-modal>
          </a-col>
        </a-row>
      </a-card>
    </a-spin>
  </page-layout>
  <BasicTableModal
    v-model:visible="schoolModal.show"
    :columns="schoolModal.columns"
    :searchForm="schoolModal.searchForm"
    @selectUniversity="handleSelectSchool"
  />
  <BasicTableModal
    title="课程选择"
    v-model:visible="modalConfig.visiableCourse"
    :columns="modalConfig.columns"
    :fetchAjax="modalConfig.api"
    :searchParams="{schName: formData.data.schName, schId: formData.data.schId}"
    :searchForm="modalConfig.searchForm"
    @selectUniversity="handleSelectModal"
  />
</template>

<script>
// import TinyMCE from "@/component/tinymce";
import BasicTableModal from "@/component/basic-table-modal";
import { getBase64, isEmpty } from "@/tools/common";
import { upload } from "@/api/module/oss";
import { save, update, selectById } from "@/api/module/courseBaseInfo";
import {
  tree,
} from "@/api/module/course-code-manage";
import { page } from "@/api/module/project";
import { reactive, ref, toRaw, onMounted, computed, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import { message } from "ant-design-vue";
import {
  coursePage,
} from "@/api/module/course-code-manage";
import { getDictByCodesReturnObj } from "@/tools/get-dict";
import dictEnum from "@/const/dict";
import moment from "moment";

import mixin from '@/mixins'
export default {
  name: "course-base-info-add",
  components: {
    // TinyMCE,
    BasicTableModal
  },
  setup() {
    const { returnRoute } = mixin.setup()
    const { t } = useI18n();
    const route = useRoute();
    const router = useRouter();
    const placeHolder = "请输入";
    const labelCol = { span: 10 };
    const formRef = ref(null);
    const sorFormRef = ref(null);
    const isLoading = ref(false);
    const previewVisible = ref(false);
    const previewImage = ref("");
    const pageType = ref("add");
    const fileList = computed(() => {
      console.log('formData.data.files: ', formData.data.files);
      return formData.data.files || []
    })
    const formData = reactive({
      data: {
        cbiSorList: [],
        describes: "",
        files: [],
        courseOnlyCode: '',
        code: '',
        schUniversityAbbreviation: '',
        courseCode: '',
        preCurriculumRelationshipList: []
      },
      subjectList: []
    });

    const addForm = () => {
      formData.data = {
        cbiSorList: [],
        describes: "",
        files: [],
        courseOnlyCode: '',
        code: '',
        schUniversityAbbreviation: '',
        courseCode: '',
        preCurriculumRelationshipList: []
      }
      // addCourseItem()
    }

    const schoolModal = reactive({
      show: false,
      dataIndex: null,
      columns: [],
      searchForm: []
    });
    const modalConfig = reactive({
      visiableCourse: false,
      columns: [],
      dataIndex: null,
      searchForm: [],
      api: coursePage
    });

    // watch(formData.data, (value) => {
    //   if (value.schUniversityAbbreviation && value.courseCode) {
    //     formData.data.courseOnlyCode = value.schUniversityAbbreviation + value.courseCode
    //   } else {
    //     formData.data.courseOnlyCode = ''
    //   }
    // }, {deep: true})

    // const requiredRules = [{ required: true, message: "请输入" }];
    // const requiredRulesS = [{ required: true, message: "请选择学校" }];
    // const requiredRulesT = [{ required: true, message: "请选择日期" }];
    const rules = {
      schName: [{ required: true, message: '请选择学校名称', trigger: 'change' }],
      courseName: [{ required: true, message: '请输入课程名称', trigger: 'change' }],
      credit: [{ required: true, message: '请输入学分', trigger: 'change' }],
      courseCode: [{ required: true, message: '请输入课程代码', trigger: 'change' }],
      disciplineId: [{ required: true, message: '请选择学科类别', trigger: 'change' }],
      describes: [{ required: true, message: '请输入课程描述', trigger: 'change' }]
    }
    const addCourseItem = () =>
      formData.data.cbiSorList.push({
        schName: "",
        schId: "",
        courseCode: "",
        courseName: "",
        auditPassTime: ""
      });
    const deleteCourseItem = sendIndex =>
      formData.data.cbiSorList.splice(sendIndex, 1);

    const handlePreview = async file => {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }

      previewImage.value = file.url || file.preview;
      previewVisible.value = true;
    };

    const handleCancel = () => (previewVisible.value = false);

    const handleUpload = data => {
      isLoading.value = true;
      const ajaxFormData = new FormData();
      ajaxFormData.append("file", data.file);
      upload(ajaxFormData)
        .then(res => {
          if (res.code === 500) {
            message.error({ content: "上传图片失败" });
          } else {
            const { path: url, id: fileId, remark, name } = res.data;
            Array.isArray(formData.data.files) && formData.data.files.push({ type: "courseThumb", url, fileId, remark, name });
          }
          isLoading.value = false;
        })
        .catch(_ => {
          isLoading.value = false;
        });
    };

    const handleChange = info =>
      (formData.data.files = info.fileList.filter(v => v.status !== "error"));

    const handleSave = async () => {
      await formRef.value.validate();
      await sorFormRef.value.validate();
      const courseBasicInformation = toRaw(formData.data);
      const { files, describes } = courseBasicInformation;
      let response,
        content = "";
      if (pageType.value === "edit") {
        response = await update({
          ...courseBasicInformation,
          id: route.query.id
        });
        content = "修改";
      } else {
        response = await save(courseBasicInformation);
        content = "新增";
      }

      if (response.code === 500) return message.error(`${content}失败`);
      message.success({
        content: `${content}成功`,
        onClose() {
          returnRoute()
        }
      });
    };

    const handleOpenSchoolModal = (type, _index) => {
      if (type == 'visiableCourse') {
        if (!formData.data.schName) return message.warning('请先选择学校名称')
        modalConfig[type] = true;
        modalConfig.dataIndex = _index;
        return;
      }
      schoolModal.show = true;
      schoolModal.type = type;
      if (type === "sor") {
        schoolModal.dataIndex = _index;
      }
    };

    const handleSelectSchool = data => {
      const { id: schId, schoolEnName, schUniversityAbbreviation } = data;

      if (schoolModal.type === "sor") {
        formData.data.cbiSorList[
          schoolModal.dataIndex
        ].schName = schoolEnName;
        formData.data.cbiSorList[schoolModal.dataIndex].schId = schId;
        schoolModal.dataIndex = null;
        // sorFormRef.value.resetFields()
      } else {
        formData.data.schId = schId;
        formData.data.schName = schoolEnName;
        formData.data.schUniversityAbbreviation = schUniversityAbbreviation;
      }

      schoolModal.type = null;
    };

    const handleSelectModal = data => {
      formData.data.preCurriculumRelationshipList[
          modalConfig.dataIndex
        ].courseName = data.courseName;
        formData.data.preCurriculumRelationshipList[modalConfig.dataIndex].courseId = data.id;
        modalConfig.dataIndex = null;
        modalConfig.visiableCourse = false;
    }

    const getSubjectPage = () => {
      return tree()
        .then((result) => {
          if (result.success) {
            formData.subjectList = result.data;
          }
        })
        .catch((err) => {
          console.log("err: ", err);
        });
    };
    getSubjectPage()


    const handleCourse = () => {
      formData.data.preCurriculumRelationshipList.push({
        courseId: null,
        courseName: null,
        relationship: null,
      });
    };

    const handleDel = (row, idx) => {
      formData.data.preCurriculumRelationshipList =
        formData.data.preCurriculumRelationshipList.filter(
          (item, index) => index != idx
        );
    };

    const openDialog = (value, index) => {
      if (index==0||index) {
        formData.itemIndex = index
      }
      formData[value] = true;
    };

    const handleTree = (value, node) => {
      if (value) {
        formData.data.disciplineName = node.dataRef.disciplineName
      }
    }

    const dictLists = reactive({
      data: {}
    });

    onMounted(async () => {
      const isEdit = !isEmpty(route.query.id);
      pageType.value = isEdit ? "edit" : "add";

      if (route.query.id) {
        const formResponse = await selectById({ id: route.query.id });
        formResponse.data.firstCourseStarttime = formResponse.data.firstCourseStarttime
                                          ? moment(formResponse.data.firstCourseStarttime).format('YYYY-MM-DD')
                                          : ''
      formResponse.data.courseLastReviewtime = formResponse.data.courseLastReviewtime
                                          ? moment(formResponse.data.courseLastReviewtime).format('YYYY-MM-DD')
                                          : ''
      formResponse.data.courseLastOpentime = formResponse.data.courseLastOpentime
                                          ? moment(formResponse.data.courseLastOpentime).format('YYYY-MM-DD')
                                          : ''
      formResponse.data.cbiSorList && formResponse.data.cbiSorList.map(item => {
        item.sorAuditTime = item.sorAuditTime
                                            ? moment(item.sorAuditTime).format('YYYY-MM-DD')
                                            : ''
                                            return item

      })
        formData.data = formResponse.data;
        // if (formData.data.cbiSorList.length === 0) addCourseItem();
      } else {
        addForm();
      }

      dictLists.data = await getDictByCodesReturnObj([
        dictEnum.FOLLOW_PROGRESS,
        dictEnum.COURSE_RELATION,
        dictEnum.COURSE_TYPE,
      ]);

      schoolModal.columns = [
        { dataIndex: "code", key: "code", title: "学校编码" },
        { dataIndex: "schoolEnName", key: "schoolEnName", title: "学校名称" },
        {
          dataIndex: "schFollowUpProgress",
          key: "schFollowUpProgress",
          title: "跟进进度",
          cellRender: (record, data) => {
            if (dictLists.data[dictEnum.FOLLOW_PROGRESS]) {
              const item = dictLists.data[dictEnum.FOLLOW_PROGRESS].find(
                v => v.value == data
              );
              return item ? item.label : "-";
            }
            return "-";
          }
        }
      ];
      schoolModal.searchForm = [
        { type: 'input', key: "schoolEnName", label: "学校名称" },
        { type: 'input', key: "code", label: "学校编码" },
      ]
      modalConfig.columns = [
        { dataIndex: "code", key: "code", title: "课程编码" },
        { dataIndex: "schName", key: "schName", title: "学校名称" },
        { dataIndex: "courseCode", key: "courseCode", title: '课程代码' },
        { dataIndex: "courseName", key: "courseName", title: t('course-manage.label.courseName') },
        // { dataIndex: "createBy", key: "createBy", title: t('label.creator') },
      ];
      modalConfig.searchForm = [
        { key: "courseCode", type: "input", label: "课程代码", placeholder: t('placeholder.pleaseEnter')},
        { key: "code", type: "input", label: "课程编码", placeholder: t('placeholder.pleaseEnter')},
      ]
    });

    return {
      t,
      formData,
      previewImage,
      previewVisible,
      placeHolder,
      labelCol,
      // requiredRules,
      // requiredRulesS,
      // requiredRulesT,
      formRef,
      sorFormRef,
      schoolModal,
      isLoading,
      dictLists,
      dictEnum,
      page,
      addCourseItem,
      deleteCourseItem,
      handleOpenSchoolModal,
      handleSelectSchool,
      handleSelectModal,
      handlePreview,
      handleCancel,
      handleUpload,
      handleSave,
      handleChange,
      handleCourse,
      handleDel,
      openDialog,
      handleTree,
      modalConfig,
      fileList,
      rules,
      replaceFields: {
        children: "child",
        title: "disciplineName",
        key: "id",
        value: "id",
      },
    };
  }
};
</script>

<style lang="less" scoped>
.thumb-item {
  border: 1px solid #F5F5F5;
  border-radius: 3px;
  img {
    width: 102px;
    height: 102px;
    object-fit: contain;
  }
}
/deep/.ant-form-item-explain-error {
  position: absolute;
  top: 30px;
}
/deep/.ant-row {
  margin-top: 10px;
}


</style>
